package cn.hy.tiny.demo.core;

import cn.hy.tiny.demo.parse.GenericTokenParser;
import cn.hy.tiny.demo.parse.ParameterMapping;
import cn.hy.tiny.demo.parse.ParameterMappingTokenHandler;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author huang.xy
 * @Description TODO
 */
public class SimpleExecutor implements Executor{

    private Connection connection ;

    @Override
    public <E> List<E> query(Configuration configuration, MapperStatement mappedStatement, Object[] param) throws Exception {
        connection = configuration.getDataSource().getConnection();
        BoundSql boundSql = getBoundSql(mappedStatement.getSql());
        String finalSql = boundSql.getSqlText();

        PreparedStatement preparedStatement = connection.prepareStatement(finalSql);
        Class<?> paramType = mappedStatement.getParamType();
        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            String property = parameterMapping.getProperty();
            Field declaredField = paramType.getDeclaredField(property);
            declaredField.setAccessible(true);
            Object value = declaredField.get(param[0]);
            preparedStatement.setObject(i +1 ,value);
        }
        Class<?> resultType = mappedStatement.getResultType();
        ResultSet resultSet = preparedStatement.executeQuery();
        List<E> result  = new ArrayList<>();
        while (resultSet.next()) {
            ResultSetMetaData metaData = resultSet.getMetaData();
            E e = (E) resultType.newInstance();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                // 列
                String columnName = metaData.getColumnName(i);
                // 值
                Object v = resultSet.getObject(columnName);
//                Field declaredField = resultType.getDeclaredField(columnName);
//                declaredField.setAccessible(true);
//                declaredField.set(o,v);
                // bean 内省
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultType);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(e,v);
            }
            result.add(e);
        }
        return result;
    }

    private BoundSql getBoundSql(String sql) {
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        //GenericTokenParser :通⽤的标记解析器，完成了代码⽚段中的占位符的解析，然后再根据给定的标记处理器(TokenHandler)来进⾏表达式的处理
        //三个参数：分别为openToken (开始标记)、closeToken (结束标记)、handler (标记处 理器)
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
        String parseSql = genericTokenParser.parse(sql);
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();
        return new BoundSql(parseSql,parameterMappings);
    }

    @Override
    public void close() throws SQLException {
        if(connection != null) {
            connection.close();
        }
    }
}
